# coding=utf-8
from rest_framework.exceptions import ValidationError
from rest_framework.viewsets import ModelViewSet

from utils import response_error, response_ok
from utils.exceptions import CustomError

from django.db import transaction


class CustomModelViewSet(ModelViewSet):
    def create(self, request, *args, **kwargs):
        try:
            with transaction.atomic():
                super(CustomModelViewSet, self).create(request, *args, **kwargs)
        except CustomError as e:
            return response_error(e.get_error_msg())
        except Exception as e:
            import traceback
            traceback.print_exc()
            return response_error(str(e))
        return response_ok()

    def update(self, request, *args, **kwargs):
        try:
            with transaction.atomic():
                super(CustomModelViewSet, self).update(request, *args, **kwargs)
        except CustomError as e:
            return response_error(e.get_error_msg())
        # except ValidationError as ve:
        #     errors = ve.get_full_details()
        #     for key in ve.get_full_details():
        #         print(errors[key][0]['message'])
        #     print('ValidationError', str(ve))
        #     return response_error(str(ve))
        except Exception as e:
            import traceback
            traceback.print_exc()
            return response_error(str(e))
        return response_ok()

    def destroy(self, request, *args, **kwargs):
        try:
            with transaction.atomic():
                super(CustomModelViewSet, self).destroy(request, *args, **kwargs)
        except CustomError as e:
            return response_error(e.get_error_msg())
        except Exception as e:
            import traceback
            traceback.print_exc()
            return response_error(str(e))
        return response_ok()

    def retrieve(self, request, *args, **kwargs):
        try:
            instance = self.get_object()
        except CustomError as e:
            return response_error(e.get_error_msg())
        except Exception as e:
            return response_error(str(e))
        serializer = self.get_serializer(instance)
        return response_ok(serializer.data)
